# -*- coding: utf-8 -*-

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.axes import Axes
from matplotlib.lines import Line2D
import matplotlib.font_manager

matplotlib.use('Qt5Agg')

def mpl_font():
    # 字体配置文件绝对路径
    # print(mpl.matplotlib_fname())
    # ttf和afm字体
    # print(matplotlib.font_manager.fontManager.ttflist)
    # print(matplotlib.font_manager.fontManager.afmlist)

    # 设置无衬线字体为宋体使得中文显示正常
    plt.rcParams['font.sans-serif'] = ['SimHei', 'Songti SC']
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
    pass


def mpl_pyplot():
    plt.title(label="plt plot")

    x = np.linspace(start=-np.pi, stop=np.pi, num=201)

    # 刻度
    plt.xticks(ticks=x[::100], labels=["-pi", "0", "pi"],
               fontname="Times New Roman", fontsize=20, )
    # plt.yticks()
    plt.ylim(bottom=-1, top=1.5)

    # 标签：坐标轴说明
    plt.xlabel(xlabel="x_axis",
               fontdict={"family": "Times New Roman", "size": 20})

    # 线条：参数不能加参数名
    sin_line: Line2D = plt.plot(x, np.sin(x), label='sin(x)')
    cos_line: Line2D = plt.plot(x, np.cos(x), label='cos(x)')

    plt.legend(loc='upper center', ncol=2,
               prop={"family": "Times New Roman", "size": 20})

    # 紧凑布局
    plt.tight_layout()

    # 保存：指定路径
    # plt.savefig("plt.png")

    # 显示图表
    plt.show()
    # 关闭所有
    plt.close('all')

    pass


def mpl_figure():
    dpi = 100
    # 图形：设置尺寸和像素
    fig: Figure = plt.figure(figsize=(8, 6), dpi=dpi)
    """
    figsize=(w, h)
    dpi=d
    width=d*w
    height=d*h
    """
    # fig, ax = plt.subplots()
    # ax: Axes = plt.subplot()

    # ax: Axes = fig.subplots()
    # ax: Axes = fig.add_subplot()

    # ax: Axes = fig.add_axes()
    # fig.axes

    # get current axes
    ax = fig.gca()

    x = np.linspace(start=-np.pi, stop=np.pi, num=201)
    line: Line2D = ax.plot(x, np.sin(x))

    # fig.savefig(fname="fig.png", dpi=dpi)
    fig.show()

    plt.close(fig=fig)

    pass


def mpl_axes():
    ax: Axes = plt.subplot()

    x = np.linspace(start=-np.pi, stop=np.pi, num=201)
    line: Line2D = ax.plot(x, np.sin(x))

    ax.set_title(label='标题', fontdict={'family': 'Times New Roman', 'size': 25})
    ax.annotate(text='注释', xy=(np.pi / 2, 1), xytext=(np.pi, 1),
                arrowprops=dict(facecolor='black', shrink=0.05), )

    plt.show()
    plt.close()

    pass


def demo01():
    fig, ax = plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal"))

    recipe = ["225 g flour",
              "90 g sugar",
              "1 egg",
              "60 g butter",
              "100 ml milk",
              "1/2 package of yeast",
              "2/2 package of yeast", ]

    data = [225, 90, 50, 60, 100, 5, 8]

    wedges, texts = ax.pie(data)

    bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
    kw = dict(arrowprops=dict(arrowstyle="-"),
              bbox=bbox_props, zorder=0, va="center")

    for i, p in enumerate(wedges):
        ang = (p.theta2 - p.theta1) / 2. + p.theta1
        y = np.sin(np.deg2rad(ang))
        x = np.cos(np.deg2rad(ang))
        horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
        connectionstyle = "angle,angleA=0,angleB={}".format(ang)
        kw["arrowprops"].update({"connectionstyle": connectionstyle})
        ax.annotate(recipe[i], xy=(x, y), xytext=(1.35 * np.sign(x), 1.4 * y),
                    horizontalalignment=horizontalalignment, **kw)

    ax.set_title("Matplotlib bakery: A donut")

    plt.show()
    pass


if __name__ == '__main__':
    mpl_font()
    mpl_pyplot()
    # mpl_figure()
    # mpl_axes()

    # demo01()

    pass
